package com.forum.impl.forum;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.entity.ApiResult;
import com.common.utils.LocalContext;
import com.forum.mapper.forum.ForumUserMapper;
import com.forum.param.ForumUserPasswordParam;
import com.forum.param.ForumUserUpdateInfoParam;
import com.forum.param.LoginParam;
import com.forum.pojo.forum.ForumUser;
import com.forum.service.forum.ForumUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Tsing
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ForumUserServiceImpl extends ServiceImpl<ForumUserMapper, ForumUser> implements ForumUserService {
    private final ForumUserMapper forumUserMapper;

    @Value("${security.slat}")
    private String slat;

    @Override
    //TODO 邮箱验证码待做
    public ApiResult<String> register(LoginParam param) {
        //MD5密码加密
        String pwd = DigestUtils.md5DigestAsHex((param.getPassword() + slat).getBytes());
        ForumUser forumUser = new ForumUser(param.getStuId(),param.getNickname(),param.getEmail(),pwd);
        forumUserMapper.insert(forumUser);
        StpUtil.login(forumUser.getId());
        String tokenValue = StpUtil.getTokenValueByLoginId(forumUser.getId());
        //存储当前登录的用户ID到当前线程
        LocalContext.remove();
        LocalContext.setCurrentUserId(forumUser.getId());
        return ApiResult.success(tokenValue);
    }

    @Override
    public ApiResult<?> login(LoginParam param) {
        LambdaQueryWrapper<ForumUser> queryWrapper = new LambdaQueryWrapper<>();
        String pwd = DigestUtils.md5DigestAsHex((param.getPassword()+slat).getBytes());
        queryWrapper.eq(ForumUser::getStuId,param.getStuId())
                .eq(ForumUser::getPassword,pwd);
        ForumUser forumUser = forumUserMapper.selectOne(queryWrapper);
        if(!Objects.isNull(forumUser)){
            StpUtil.login(forumUser.getId());
            forumUser.setPassword("");
            StpUtil.getSession().set("userInfo",forumUser);
            //存储当前登录的用户ID到当前线程
            LocalContext.remove();
            LocalContext.setCurrentUserId(forumUser.getId());
            Map<String,Object>map = new HashMap<>(16);
            map.put("token",StpUtil.getTokenValueByLoginId(forumUser.getId()));
            map.put("userInfo",forumUser);
            return ApiResult.success(map);
        }
        return ApiResult.fail(HttpStatus.UNAUTHORIZED.value(),"登录信息错误");
    }

    @Override
    public ApiResult<String> editUserInfo(ForumUserUpdateInfoParam userUpdateInfoParam) {
        Integer currentUserId = LocalContext.getCurrentUserId();
        ForumUser forumUser = forumUserMapper.selectById(currentUserId);
        BeanUtils.copyProperties(userUpdateInfoParam,forumUser);
        forumUserMapper.updateById(forumUser);
        StpUtil.login(forumUser.getId());
        StpUtil.getSession().set("userInfo",forumUser);
        return ApiResult.success();
    }

    @Override
    public ApiResult<String> updateUserPassword(ForumUserPasswordParam passwordParam) {
        String oldPwd = DigestUtils.md5DigestAsHex((passwordParam.getOldPassword()+slat).getBytes());
        Integer currentUserId = LocalContext.getCurrentUserId();
        ForumUser forumUser = forumUserMapper.selectById(currentUserId);
        if(!forumUser.getPassword().equals(oldPwd)){
            return ApiResult.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(),"原密码不正确");
        }
        String newPassword = DigestUtils.md5DigestAsHex((passwordParam.getNewPassword()+slat).getBytes());
        forumUser.setPassword(newPassword);
        forumUserMapper.updateById(forumUser);
        StpUtil.logout(forumUser.getId());
        StpUtil.login(forumUser.getId());
        LocalContext.remove();
        LocalContext.setCurrentUserId(forumUser.getId());
        return ApiResult.success(StpUtil.getTokenValueByLoginId(forumUser.getId()));
    }

    @Override
    public ApiResult<ForumUser> getCurrentUser() {
        Integer currentUserId = LocalContext.getCurrentUserId();
        ForumUser forumUser = forumUserMapper.selectById(currentUserId);
        return ApiResult.success(forumUser);
    }
}
